package com.wind.framework.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author： BeiYan
 * @Date： 2016-11-27 15:17
 * @Description:json工具类
 */

public final class JsonUtil {

    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将POJO转为Json
     */
    public static <T> String toJson(T obj) {
        String json;
        try {
            json = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("parse object to json failure", e);
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * 将Json转为POJO
     */
    public static <T> T fromJson(String json, Class<T> type) {
        T pojo;
        try {
            pojo = objectMapper.readValue(json, type);
        } catch (IOException e) {
            logger.error("from json failure", e);
            throw new RuntimeException(e);
        }
        return pojo;
    }

}

